
package android_serialport_api;

import android.util.Log;

import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import com.richapp.launcher.serialport.gateway.GatewaytConstant;

public class SerialPort {

    private static final String TAG = SerialPort.class.getName();

    /**
     * 加载底层驱动库
     */
    static {
        System.loadLibrary(GatewaytConstant.SERIAL_PORT_DRIVER_NAME);
    }

    private FileInputStream mFileInputStream;
    private FileOutputStream mFileOutputStream;

    /**
     * 打开设备
     *
     * @param path     路径
     * @param baudrate 比特率
     * @param flags
     * @return 文件描述
     */
    private native static FileDescriptor open(String path, int baudrate, int flags);

    /**
     * 关闭设备
     */
    public native void close();

    public SerialPort(File device, int baudrate, int flags) throws Exception {
        try {
            //检查设备读写权限
            if (!device.canRead() || !device.canWrite()) {
                //如果设备不可读或者不可写，尝试修改设备权限
                Process su = Runtime.getRuntime().exec("/system/bin/su");
                String cmd = "chmod 666 " + device.getAbsolutePath() + "\n" + "exit\n";
                su.getOutputStream().write(cmd.getBytes());
                if ((su.waitFor() != 0) || !device.canRead() || !device.canWrite()) {
                    //如果修改权限失败，抛出安全异常
                    throw new SecurityException();
                }
            }

            //执行到这里表示设备可读写
            FileDescriptor mFd = open(device.getAbsolutePath(), baudrate, flags);
            if (mFd == null) {
                Log.e(TAG, "打开设备错误!");
                throw new IOException();
            }
            mFileInputStream = new FileInputStream(mFd);
            mFileOutputStream = new FileOutputStream(mFd);
            Log.d(TAG, "串口初始化成功");
        } catch (Exception e) {
            Log.e(TAG, "串口初始化失败:" + e.getMessage());
            throw new Exception(e.getMessage());
        }
    }

    /**
     * 获取设备输出流
     *
     * @return
     */
    public InputStream getInputStream() {
        return mFileInputStream;
    }

    /**
     * 获取设备输入流
     *
     * @return
     */
    public OutputStream getOutputStream() {
        return mFileOutputStream;
    }
}
